/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.osiris.persistence.controllers.impl;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import org.osiris.persistence.Categoria;
import org.osiris.persistence.Subcategoria;
import java.util.ArrayList;
import java.util.List;

import org.osiris.persistence.controllers.CategoriasInterface;
import org.osiris.persistence.controllers.exceptions.IllegalOrphanException;
import org.osiris.persistence.controllers.exceptions.NonexistentEntityException;
import org.osiris.persistence.controllers.exceptions.PreexistingEntityException;

/**
 *
 * @author amartinez
 */
public class CategoriaJpaController implements CategoriasInterface {

    public CategoriaJpaController() {
    	emf = CreadorPU.getEntityManagerFactory();
    }
    private EntityManagerFactory emf = null;

    /* (non-Javadoc)
	 * @see org.osiris.persistence.controllers.CategoriasInterface#getEntityManager()
	 */
    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    /* (non-Javadoc)
	 * @see org.osiris.persistence.controllers.CategoriasInterface#create(org.osiris.persistence.Categoria)
	 */
    public void create(Categoria categoria) throws PreexistingEntityException, Exception {
        if (categoria.getSubcategoriaList() == null) {
            categoria.setSubcategoriaList(new ArrayList<Subcategoria>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Subcategoria> attachedSubcategoriaList = new ArrayList<Subcategoria>();
            for (Subcategoria subcategoriaListSubcategoriaToAttach : categoria.getSubcategoriaList()) {
                subcategoriaListSubcategoriaToAttach = em.getReference(subcategoriaListSubcategoriaToAttach.getClass(), subcategoriaListSubcategoriaToAttach.getIdSubcategoria());
                attachedSubcategoriaList.add(subcategoriaListSubcategoriaToAttach);
            }
            categoria.setSubcategoriaList(attachedSubcategoriaList);
            em.persist(categoria);
            for (Subcategoria subcategoriaListSubcategoria : categoria.getSubcategoriaList()) {
                Categoria oldIdCategoriaOfSubcategoriaListSubcategoria = subcategoriaListSubcategoria.getIdCategoria();
                subcategoriaListSubcategoria.setIdCategoria(categoria);
                subcategoriaListSubcategoria = em.merge(subcategoriaListSubcategoria);
                if (oldIdCategoriaOfSubcategoriaListSubcategoria != null) {
                    oldIdCategoriaOfSubcategoriaListSubcategoria.getSubcategoriaList().remove(subcategoriaListSubcategoria);
                    oldIdCategoriaOfSubcategoriaListSubcategoria = em.merge(oldIdCategoriaOfSubcategoriaListSubcategoria);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findCategoria(categoria.getIdCategoria()) != null) {
                throw new PreexistingEntityException("Categoria " + categoria + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    /* (non-Javadoc)
	 * @see org.osiris.persistence.controllers.CategoriasInterface#edit(org.osiris.persistence.Categoria)
	 */
    public void edit(Categoria categoria) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Categoria persistentCategoria = em.find(Categoria.class, categoria.getIdCategoria());
            List<Subcategoria> subcategoriaListOld = persistentCategoria.getSubcategoriaList();
            List<Subcategoria> subcategoriaListNew = categoria.getSubcategoriaList();
            List<String> illegalOrphanMessages = null;
            for (Subcategoria subcategoriaListOldSubcategoria : subcategoriaListOld) {
                if (!subcategoriaListNew.contains(subcategoriaListOldSubcategoria)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Subcategoria " + subcategoriaListOldSubcategoria + " since its idCategoria field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Subcategoria> attachedSubcategoriaListNew = new ArrayList<Subcategoria>();
            for (Subcategoria subcategoriaListNewSubcategoriaToAttach : subcategoriaListNew) {
                subcategoriaListNewSubcategoriaToAttach = em.getReference(subcategoriaListNewSubcategoriaToAttach.getClass(), subcategoriaListNewSubcategoriaToAttach.getIdSubcategoria());
                attachedSubcategoriaListNew.add(subcategoriaListNewSubcategoriaToAttach);
            }
            subcategoriaListNew = attachedSubcategoriaListNew;
            categoria.setSubcategoriaList(subcategoriaListNew);
            categoria = em.merge(categoria);
            for (Subcategoria subcategoriaListNewSubcategoria : subcategoriaListNew) {
                if (!subcategoriaListOld.contains(subcategoriaListNewSubcategoria)) {
                    Categoria oldIdCategoriaOfSubcategoriaListNewSubcategoria = subcategoriaListNewSubcategoria.getIdCategoria();
                    subcategoriaListNewSubcategoria.setIdCategoria(categoria);
                    subcategoriaListNewSubcategoria = em.merge(subcategoriaListNewSubcategoria);
                    if (oldIdCategoriaOfSubcategoriaListNewSubcategoria != null && !oldIdCategoriaOfSubcategoriaListNewSubcategoria.equals(categoria)) {
                        oldIdCategoriaOfSubcategoriaListNewSubcategoria.getSubcategoriaList().remove(subcategoriaListNewSubcategoria);
                        oldIdCategoriaOfSubcategoriaListNewSubcategoria = em.merge(oldIdCategoriaOfSubcategoriaListNewSubcategoria);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = categoria.getIdCategoria();
                if (findCategoria(id) == null) {
                    throw new NonexistentEntityException("The categoria with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    /* (non-Javadoc)
	 * @see org.osiris.persistence.controllers.CategoriasInterface#destroy(java.lang.Long)
	 */
    public void destroy(Long id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Categoria categoria;
            try {
                categoria = em.getReference(Categoria.class, id);
                categoria.getIdCategoria();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The categoria with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Subcategoria> subcategoriaListOrphanCheck = categoria.getSubcategoriaList();
            for (Subcategoria subcategoriaListOrphanCheckSubcategoria : subcategoriaListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Categoria (" + categoria + ") cannot be destroyed since the Subcategoria " + subcategoriaListOrphanCheckSubcategoria + " in its subcategoriaList field has a non-nullable idCategoria field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(categoria);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    /* (non-Javadoc)
	 * @see org.osiris.persistence.controllers.CategoriasInterface#findCategoriaEntities()
	 */
    public List<Categoria> findCategoriaEntities() {
        return findCategoriaEntities(true, -1, -1);
    }

    /* (non-Javadoc)
	 * @see org.osiris.persistence.controllers.CategoriasInterface#findCategoriaEntities(int, int)
	 */
    public List<Categoria> findCategoriaEntities(int maxResults, int firstResult) {
        return findCategoriaEntities(false, maxResults, firstResult);
    }

    private List<Categoria> findCategoriaEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Categoria as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    /* (non-Javadoc)
	 * @see org.osiris.persistence.controllers.CategoriasInterface#findCategoria(java.lang.Long)
	 */
    public Categoria findCategoria(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Categoria.class, id);
        } finally {
            em.close();
        }
    }

    /* (non-Javadoc)
	 * @see org.osiris.persistence.controllers.CategoriasInterface#getCategoriaCount()
	 */
    public int getCategoriaCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Categoria as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
